

(function($){
	$.fn.pagination = function(opts){
		var setting = {
			first$:"li.j-first", prev$:"li.j-prev", next$:"li.j-next", last$:"li.j-last", nums$:"li.j-num>a", jumpto$:"li.jumpto",
			pageNumFrag:'<li class="#liClass#"><a href="#">#pageNum#</a></li>'
		};
		return this.each(function(){
			var $this = $(this);
			var pc = new Pagination(opts);
			var interval = pc.getInterval();

			var pageNumFrag = '';
			for (var i=interval.start; i<interval.end;i++){
				pageNumFrag += setting.pageNumFrag.replaceAll("#pageNum#", i).replaceAll("#liClass#", i==pc.getCurrentPage() ? 'selected j-num' : 'j-num');
			}
			
			var html='<ul>'+
				'<li class="j-first"><a class="first" href="#"><span>首页</span></a><span class="first"><span>首页</span></span></li>'+
		        '<li class="j-prev"><a class="previous" href="#"><span>上一页</span></a><span class="previous"><span>上一页</span></span></li>'+
		        '#pageNumFrag#'+
		        '<li class="j-next"><a class="next" href="#"><span>下一页</span></a><span class="next"><span>下一页</span></span></li>'+
		        '<li class="j-last"><a class="last" href="#"><span>末页</span></a><span class="last"><span>末页</span></span></li>'+
		        '<li class="jumpto"><input class="textInput" type="text" size="4" value="#currentPage#" /><input class="goto" type="button" value="确定" /></li>'+
	            '</ul>';
			$this.html(html.replaceAll("#pageNumFrag#", pageNumFrag).replaceAll("#currentPage#", pc.getCurrentPage())).find("li").hoverClass();

			var $first = $this.find(setting.first$);
			var $prev = $this.find(setting.prev$);
			var $next = $this.find(setting.next$);
			var $last = $this.find(setting.last$);
			
			if (pc.hasPrev()){
				$first.add($prev).find(">span").hide();
				_bindEvent($prev, pc.getCurrentPage()-1, pc.targetType());
				_bindEvent($first, 1, pc.targetType());
			} else {
				$first.add($prev).addClass("disabled").find(">a").hide();
			}
			
			if (pc.hasNext()) {
				$next.add($last).find(">span").hide();
				_bindEvent($next, pc.getCurrentPage()+1, pc.targetType());
				_bindEvent($last, pc.numPages(), pc.targetType());
			} else {
				$next.add($last).addClass("disabled").find(">a").hide();
			}           		
			$this.find(setting.nums$).each(function(i){
				_bindEvent($(this), i+interval.start, pc.targetType());
			});
			$this.find(setting.jumpto$).each(function(){
				var $this = $(this);
				var $inputBox = $this.find(":text");
				var $button = $this.find(":button");
				$button.click(function(event){
					var pageNum = $inputBox.val();
					if (pageNum && pageNum.isPositiveInteger()) {
						if (pc.targetType() == "jbox") {
							dialogPageBreak({pageNum:pageNum});
						} 
						if(pc.targetType() == "navTab") {
							navTabPageBreak({pageNum:pageNum});
						}
						if(pc.targetType() == "common"){
							commonPageBreak(opts.jParent,{pageNum:pageNum});
						}
					}
				});
				$inputBox.keyup(function(event){
					if (event.keyCode == NFE.keyCode.ENTER) $button.click();
				});
			});
		});
		
		function _bindEvent(jTarget, pageNum, targetType){
			jTarget.bind("click", {pageNum:pageNum}, function(event){
				if (targetType == "jbox") {
					dialogPageBreak({pageNum:event.data.pageNum});
				} 
				if(targetType == "navTab"){
					navTabPageBreak({pageNum:event.data.pageNum});
				}
				if(targetType == "common"){
					commonPageBreak(opts.jParent,{pageNum:event.data.pageNum});
				}
				event.preventDefault();
			});
		}
	}

	var Pagination = function(opts) {
		this.opts = $.extend({
			targetType:"navTab",	// navTab, dialog
			totalCount:0,
			numPerPage:10,
			pageNumShown:10,
			currentPage:1,
			callback:function(){return false;}
		}, opts);
	};
	
	$.extend(Pagination.prototype, {
		targetType:function(){return this.opts.targetType},
		numPages:function() {
			var newNumPage = $('#'+this.opts.jParent).find('input[name=numPerPage]').val()||this.opts.numPerPage;
			//return Math.ceil(this.opts.totalCount/this.opts.numPerPage);
			return Math.ceil(this.opts.totalCount/newNumPage);
		},
		getInterval:function(){
			var ne_half = Math.ceil(this.opts.pageNumShown/2);
			var np = this.numPages();
			var upper_limit = np - this.opts.pageNumShown;
			var start = this.getCurrentPage() > ne_half ? Math.max( Math.min(this.getCurrentPage() - ne_half, upper_limit), 0 ) : 0;
			var end = this.getCurrentPage() > ne_half ? Math.min(this.getCurrentPage()+ne_half, np) : Math.min(this.opts.pageNumShown, np);
			return {start:start+1, end:end+1};
		},
		getCurrentPage:function(){
			var currentPage = parseInt(this.opts.currentPage);
			if (isNaN(currentPage)) return 1;
			return currentPage;
		},
		hasPrev:function(){
			return this.getCurrentPage() > 1;
		},
		hasNext:function(){
			return this.getCurrentPage() < this.numPages();
		}
	});
})(jQuery);

function pagination_init(){
	$("div.pagination").each(function(){
		var $this = $(this);
		$this.pagination({
			targetType:$this.attr("targetType"),
			totalCount:$this.attr("totalCount"),
			numPerPage:$this.attr("numPerPage"),
			pageNumShown:$this.attr("pageNumShown"),
			currentPage:$this.attr("currentPage"),
			jParent:$this.attr("jParent")
		});
	});
}

function _getPagerForm($parent, args) {
	var form = $("#pagerForm", $parent).get(0);
	
	if (form) {
		args = args || {};
		if(args["pageNum"])form.pageNum.value = args["pageNum"];
		if(args["numPerPage"])form.numPerPage.value = args["numPerPage"];
		if(args["orderField"])form.orderField.value = args["orderField"];
	}
	
	return form;
}
function navTabPageBreak(args){
	var form = _getPagerForm(navTab.getCurrentPanel(), args);
	if (form) navTab.reload(form.action, $(form).serializeArray());
}
function jboxPageBreak(args){
	var form = _getPagerForm($.jbox.getCurrent(), args);
	if (form) $.jbox.reload(form.action, $(form).serializeArray());
}
function commonPageBreak(jParent,args){
	var form = _getPagerForm($('#'+jParent), args);
	if(form){		
		$.post(form.action,$(form).serializeArray(),function(result){
			pageFix(jParent,result);
		});
	}
}

function pageFix(jParent,result){
	var res = result;
	res = res.replace(/(^\s*)|(\s*$)/g,""); 
	var begin = res.indexOf("<!--AjaxTableBegin-->");
	var end = res.indexOf("<!--AjaxTableEnd-->");
	res = res.substring(begin,end+19);
    $('#AjaxTable',$('#'+jParent)).html(res);
	if(typeof(cssTableHover) == "function"){
		cssTableHover();
	}
	if(typeof(pager_callback) == "function"){
		pager_callback();
	}
	pagination_init();
	return false;
}
